package com.gouaixin.bee.beeframework2.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

//import com.BeeFramework.view.ImageView;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbImageUtil;
import com.ab.util.AbToastUtil;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.bean.USER;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * Created by Administrator on 2015/3/10.
 */
//上传头像界面
public class B19_shangchuanTouxiangActivity extends FragmentActivity {
    Context context = B19_shangchuanTouxiangActivity.this;

    ImageView upload;//上传头像
    LinearLayout xiangce;//相册
    LinearLayout paizhao;//拍照

    String file_path;//图片路径
    String file_path2;//裁剪后的图片路径

    boolean isLiaotian;//是否是从聊天界面跳过来的

    protected ImageLoader imageLoader = ImageLoader.getInstance();

    String icon="";//保存的头像网址


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b19_shangchuantouxiang);

        initIntent();

        initHead();
        initContent();

    }



    private void initIntent() {
        Intent it=getIntent();
        isLiaotian=it.getBooleanExtra("isLiaotian",false);

        //读取本地保存的icon
        icon= PreferencesUtils.getString(context, "icon", "");


    }


    /**
     * 内容区域的监听
     */
    private void initContent() {
        upload = (ImageView) findViewById(R.id.upload);
        xiangce = (LinearLayout) findViewById(R.id.xiangce);
        paizhao = (LinearLayout) findViewById(R.id.paizhao);

        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View mView = LayoutInflater.from(context).inflate(R.layout.dialog_xuanzetupian, null);
                AbDialogUtil.showDialog(mView);
//
                TextView lijiPaizhao = (TextView) mView.findViewById(R.id.lijipaizhao);
                TextView bendiXiangce = (TextView) mView.findViewById(R.id.bendixiangce);
                lijiPaizhao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        //下面这句指定调用相机拍照后的照片存储的路径
                        file_path=new Date().getTime()+".png";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                                .fromFile(new File(Environment
                                        .getExternalStorageDirectory(),
                                        file_path)));
                        startActivityForResult(intent, 1);
                        AbDialogUtil.removeDialog(context);
                    }
                });
                bendiXiangce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent intent2 = new Intent();
                        intent2.setType("image/*");
                        intent2.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intent2, 2);
                        AbDialogUtil.removeDialog(context);
                    }
                });

            }
        });

        xiangce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent2 = new Intent();
                intent2.setType("image/*");
                intent2.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent2, 2);


            }
        });

        paizhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                //下面这句指定调用相机拍照后的照片存储的路径
                file_path=new Date().getTime()+".png";
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        .fromFile(new File(Environment
                                .getExternalStorageDirectory(),
                                file_path)));
                startActivityForResult(intent, 1);
                AbDialogUtil.removeDialog(context);


            }
        });


        //头像存在
        if (!icon.equals("")) {
            mLog.e("头像的网址:" + icon);

            imageLoader.displayImage(icon, upload);

        } else {
            mLog.e("头像不存在：");
        }


    }

    /**
     * 头部的监听
     */
    private void initHead() {
        //顶部
        ImageView back;//返回
        TextView title;//标题
        TextView right;//右边


        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.title);
        right = (TextView) findViewById(R.id.right);

        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("进入主界面");
                tiaozhuan();

            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.e("进入主界面");
                Intent it = new Intent().setClass(context, MyMainActivity.class);
                startActivity(it);
                finish();
            }
        });

    }

    /***
     * 跳转界面的方法
     */
    private void tiaozhuan() {
        if(isLiaotian==true){
            finish();
        }else {
            Intent it = new Intent().setClass(context, MyMainActivity.class);
            startActivity(it);
            finish();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // 如果是直接从相册获取
            case 2:
                if(data != null){
                    startPhotoZoom(data.getData());
                }
                break;
            // 如果是调用相机拍照时
            case 1:
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/"+file_path);
                startPhotoZoom(Uri.fromFile(temp));
                break;
            // 取得裁剪后的图片
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只
                 * 在这个地方加下，大家可以根据不同情况在合适的
                 * 地方做判断处理类似情况
                 *
                 */
                if(data != null){
                    setPicToView(data);
                }
                break;
            default:
                break;

        }




    }

    private void uploadBitmap(final Bitmap bitmap) {

        upload.setImageBitmap(bitmap);
        mLog.e("进入上传图片的方法：");

        file_path2=new Date().getTime()+".png";

        if (saveBitmap2file(bitmap, file_path2)) {
            mLog.e("图片转文件成功：" + file_path2);

            final BmobFile file = new BmobFile(new File("/sdcard/" + file_path2));

//            mLog.e("文件转bomb成功：url=" + file.getFileUrl(context));





            file.upload(context, new UploadFileListener() {
                @Override
                public void onProgress(Integer integer) {
                    mLog.e("文件上传成功进度：" + integer);
                    AbDialogUtil.showProgressDialog(context, integer, "正在上传……");
                }

                @Override
                public void onSuccess() {
                    mLog.e("文件上传成功：" + file_path2);
                    upload.setImageBitmap(AbImageUtil.toRoundBitmap(bitmap));
                    PreferencesUtils.putString(context, "icon", file.getFileUrl(context));

                    USER myuser = BmobUser.getCurrentUser(context, USER.class);
                    myuser.setIcon(file);
                    myuser.update(context, new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            AbToastUtil.showToast(context, "更新用户头像成功");
                            PreferencesUtils.putString(context, "icon", file.getFileUrl(context));

                        }

                        @Override
                        public void onFailure(int i, String s) {

                        }
                    });

                }

                @Override
                public void onFailure(int i, String s) {
                    AbToastUtil.showToast(context,"网络故障，请稍后再试");
                    mLog.e("文件上传失败：" + s);

                }
            });


        } else {
            mLog.e("图片转文件失败：");
        }


    }


    protected String getAbsoluteImagePath(Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri,
                proj,                 // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null);                 // Order-by clause (ascending by jid)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 保存Bitmapda到本地sd卡
     * @param bmp
     * @param filename
     * @return
     */
    boolean saveBitmap2file(Bitmap bmp, String filename) {
        Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
        int quality = 100;
        OutputStream stream = null;
        try {
            stream = new FileOutputStream("/sdcard/" + filename);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return bmp.compress(format, quality, stream);
    }

    /**
     * 监听返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        long currentTime = System.currentTimeMillis();

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            tiaozhuan();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 裁剪图片方法实现
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");

            mLog.e("显示裁剪后的图片：");


            uploadBitmap(photo);

        }
    }




}
